<?php
class cmd_order extends mdl_order{

    function create(&$aCart,&$aMember,&$aDelivery,&$aPayment,&$minfo,&$postInfo ){
        $oSale = $this->system->loadModel('trading/sale');
        $trading = $oSale->getCartObject($aCart,$aMember['member_lv_id'],true,true);

        //保存收货人地址
        $this->_saveAddr($aMember['member_id'], $aDelivery);

        $iProduct = 0;
        if (is_array($trading['products']) && count($trading['products'])){
            $objGoods = $this->system->loadModel('trading/goods');    //生成订单前检查库存
            $arr = array();
            $aLinkId = array();
            foreach($trading['products'] as $k => $p){
                $aStore = $objGoods->getFieldById($p['goods_id'], array('marketable','disabled'));
                if($aStore['marketable'] == 'false' || $aStore['disabled'] == 'true'){
                    /**
                     * trigger Smarty error
                     *
                     * @param string $error_msg
                     * @param integer $error_type
                     */
                    trigger_error($p['name'].'商品未发布不能下单。',E_USER_ERROR);
                    return false;
                    exit;
                }
/*                $gStore = intval($aStore['store']) - intval($aStore['freez']);
                if(!is_null($aStore['store']) && $gStore < $p['nums']){
                    trigger_error("商品“".$aStore['name']."”库存不足",E_USER_ERROR);
                    return false;
                    exit;
                }

                //判断配件库存to检查变量
                if(count($p['adjList'])){
                    $objCart = $this->system->loadModel('trading/cart');
                    foreach($p['adjList'] as $pid => $num){
                        if(!$objCart->_checkStore($pid, $num*$p['nums'])){
                            trigger_error("商品配件库存不足",E_USER_ERROR);
                            return false;
                            exit;
                        }
                    }
                }*/
                $arr[] = $p['name'].'('.$p['nums'].')';
                $this->itemnum+=$p['nums'];
                $aLinkId[] = $p['goods_id'];
                $trading['products'][$k]['addon']['minfo'] = $minfo[$p['product_id']];    //将商品用户信息存入addon
                $trading['products'][$k]['minfo'] = $minfo[$p['product_id']];    //将商品用户信息存入addon

                if($p['goods_id']) $aP[] = $p['goods_id'];
                $iProduct++;
            }
        }
        if($trading['package'] || $trading['gift_e']) $otherPhysical = true;
        else $otherPhysical = false;
        if(count($aP) || $otherPhysical){
            $return = $this->checkOrderDelivery($aP, $aDelivery, $otherPhysical, $aMember['member_id']);    //检测实体商品配送信息的合法性
            if($return){
                $aDelivery['is_delivery'] = $return;
                if($return == 'Y' && empty($aDelivery['shipping_id'])){
                    trigger_error("提交不成功，请选择配送方式",E_USER_ERROR);
                    return false;
                    exit;
                }
            }else{
                trigger_error("对不起，请完整填写配送信息",E_USER_ERROR);
                return false;
                exit;
            }
        }

        $iPackage = 0;
        if (is_array($trading['package']) && count($trading['package'])){
            $objCart = $this->system->loadModel('trading/cart');
            foreach ($trading['package'] as $v) {
                if (!$objCart->_checkStore($v['goods_id'], $v['nums'])) {
                    trigger_error("捆绑商品库存不足",E_USER_ERROR);
                    return false;
                    exit;
                }
                $iPackage++;
                $arr[] = $v['name'].'('.$v['nums'].')';
            }
        }
        if(is_array($trading['gift_e']) && count($trading['gift_e'])){
            foreach ($trading['gift_e'] as $v){
                $arr[] = $v['name'].'('.$v['nums'].')';
            }
        }
        if($iProduct + $iPackage + count($trading['gift_p']) + count($trading['gift_e']) == 0){
            trigger_error("购物车中无有效商品!",E_USER_ERROR);
            return false;
        }

//        $objProduct->updateRate($aLinkId);    //更新商品推荐度
        $oCur = $this->system->loadModel('system/cur');
        $tdelivery = explode( ':' , $aDelivery['ship_area'] );
        $area_id = $tdelivery[count($tdelivery)-1];
        $oDelivery = $this->system->loadModel('trading/delivery');
        $rows = $oDelivery->getDlTypeByArea($area_id,$trading['weight'],$aDelivery['shipping_id']);
        if($trading['exemptFreight'] == 1){    //[exemptFreight] => 1免运费
            $aDelivery['cost_freight']=0;
        }else{
            $trading['cost_freight'] = $oCur->formatNumber(cal_fee($rows[0]['expressions'],$trading['weight'],$trading['pmt_b']['totalPrice'],$rows[0]['price']));
        }
        $trading['cost_freight'] = is_null($trading['cost_freight'])?0:$trading['cost_freight'];
        if($aDelivery['is_protect'][$aDelivery['shipping_id']] && $rows[0]['protect']==1){
            $aDelivery['cost_protect'] = $oCur->formatNumber(max($trading['totalPrice']*$rows[0]['protect_rate'],$rows[0]['minprice']));
            $aDelivery['is_protect'] = 'true';
        }else{
            $aDelivery['cost_protect']=0;
            $aDelivery['is_protect'] = 'false';
        }
        if($aPayment['payment'] > 0 || $aPayment['payment'] == -1){
            $oPayment = $this->system->loadModel('trading/payment');
            $aPay = $oPayment->getPaymentById($aPayment['payment']);
            if($aPay['pay_type'] == 'DEPOSIT' && $aMember['member_id'] == ""){
                trigger_error("未登录客户不能选择预存款支付!",E_USER_ERROR);
                return false;
            }
            $aPayment['fee'] = $aPay['fee'];
        }else{
            trigger_error("提交不成功，未选择支付方式!",E_USER_ERROR);
            return false;
        }
        $currency = $oCur->getcur($aPayment['currency']);

        if(!$this->checkPoint($aMember['member_id'], $trading)){
            return false;
        }
        if(!$this->checkGift($trading['gift_p'])){
            return false;
        }

        $orderInfo = $trading;
		//alone add start
		if($aPay['pay_type'] == 'icbc' && !empty($postInfo['icbc_period'])){
			$orderInfo['bill_period'] = $postInfo['icbc_period'];
		}
		//alone add end
        $orderInfo['order_id'] = $this->gen_id();
        $orderInfo['cur_rate'] = ($currency['cur_rate']>0 ? $currency['cur_rate']:1);
        $orderInfo['tostr'] = addslashes(implode(',',$arr));
        $orderInfo['itemnum'] = $this->itemnum;
        getRefer($orderInfo);    //推荐下单
        $aDelivery['ship_time'] = ($aDelivery['day']=='specal' ? $aDelivery['specal_day'] : $aDelivery['day']).' '.$aDelivery['time'];
        $orderInfo = array_merge($orderInfo,$aDelivery, $aPayment);
        if( $aMember ){
            $orderInfo = array_merge($orderInfo,$aMember);
        }
        return $this->save($orderInfo, true,$postInfo);
    }

    /**
     * save
     * 保存订单，用于新建或者修改
     *
     * @param mixed $doCreate 是否为新建订单
     * @access public
     * @return void todo:目前只适用于添加！！！
     */
    function save(&$trading, $doCreate=false,&$postInfo){
        $data = $trading;
        $objDelivery = $this->system->loadModel('trading/reship');
        $oCur = $this->system->loadModel('system/cur');
        $aShipping = $objDelivery->getDlTypeById($trading['shipping_id']);
        $aArea = $objDelivery->getDlAreaById($trading['area']);
        $data['shipping'] = addslashes($aShipping['dt_name']);
        $data['shipping_area'] = addslashes($aArea['name']);
        $data['acttime'] = time();
        $data['createtime'] = time();
        $data['ip'] = remote_addr();
		//alone start
		if(!empty($trading['bill_period']))
			$data['bill_period'] = $trading['bill_period'];
		//alone end
        $trading['totalPrice'] = $oCur->formatNumber($trading['totalPrice']);
        $trading['pmt_b']['totalPrice'] = $oCur->formatNumber($trading['pmt_b']['totalPrice']);
        $data['cost_item'] = $trading['totalPrice'];
        $data['total_amount'] = $trading['totalPrice']+$trading['cost_freight']+$trading['cost_protect'];
        $data['pmt_amount'] = $trading['pmt_b']['totalPrice'] - $trading['totalPrice'];
        if($trading['is_tax'] && $this->system->getConf('site.trigger_tax')){
            $data['is_tax'] = 'true';
            $data['cost_tax'] = $trading['totalPrice'] * $this->system->getConf('site.tax_ratio');
            $data['cost_tax'] = $oCur->formatNumber($data['cost_tax']);
            $data['total_amount'] += $data['cost_tax'];
        }
        if($trading['payment'] > 0){
            $data['cost_payment'] = $data['fee'] * $data['total_amount'];
            $data['cost_payment'] = $oCur->formatNumber($data['cost_payment']);
            $data['total_amount'] += $data['cost_payment'];
        }

        $newNum = $this->getOrderDecimal($data['total_amount']);
        $data['discount'] = floatval($data['total_amount'] - $newNum);
        $data['total_amount'] = $newNum;
        $data['final_amount'] = $data['total_amount'] * $data['cur_rate'];
        $data['final_amount'] = $oCur->formatNumber($data['final_amount']);
        $data['score_g'] = intval($data['totalGainScore']);
        $data['score_u'] = intval($data['totalConsumeScore']);
        $data['last_change_time'] = time();
        if ($trading['payment']!="-1"){
            //----检测该支付方式是否还有子选项，如快钱选择银行
            $payment=$this->system->loadModel('trading/payment');
            $payment->recgextend($data,$postInfo,$extendInfo);
            $data['extend']=serialize($extendInfo);
            //------------------------------------------------
        }
        $rs = $this->db->exec('SELECT * FROM sdb_orders WHERE order_id='.$data['order_id']);
        $sql = $this->db->getUpdateSql($rs,$data,$doCreate);
        $this->_info['order_id'] = $data['order_id'];        //会员id
        if(!$this->db->exec($sql)){
            return false;
        }elseif($doCreate){
            $this->addLog('订单创建', $this->op_id?$this->op_id:null, $this->op_name?$this->op_name:null , '添加' );
        }
		//alone remove start
		/*
        $status = $this->system->loadModel('system/status');
        $status->add('ORDER_NEW');
        $status->count_order_to_pay();
        $status->count_order_new();
		*/
		//alone remove end
        //+商品------------------------------------------------------------
        if (!empty($trading['products']) && is_array($trading['products'])) {
            $objGoods = $this->system->loadModel('trading/goods');
            foreach ($trading['products'] as $product) {
                $product['order_id'] = $data['order_id'];
                $product['bn'] = addslashes($product['bn']);
                $product['name'] = addslashes($product['name']);
                $product['addon'] = addslashes(serialize($product['addon']));
                $product['minfo'] = addslashes(serialize($product['minfo']));
                $rs = $this->db->query('SELECT * FROM sdb_order_items WHERE 0=1');
                $sqlString = $this->db->GetInsertSQL($rs, $product);
                if($sqlString) $this->db->exec($sqlString);
                $objGoods->updateRank($product['goods_id'], 'buy_count', $product['nums']);    //购买次数统计
                //冻结库存
                $this->db->exec("UPDATE sdb_products SET freez = freez + ".intval($product['nums'])." WHERE product_id = ".intval($product['product_id']));
                $this->db->exec("UPDATE sdb_products SET freez = ".intval($product['nums'])." WHERE product_id = ".intval($product['product_id'])." AND freez IS NULL");
            }
        }

        //+捆绑商品------------------------------------------------------------
        if (is_array($trading['package']) && count($trading['package'])) {
            foreach ($trading['package'] as $pkgData) {
                $pkgData['order_id'] = $data['order_id'];
				//alone remove start
                //$pkgData['bn'] = addslashes($pkgData['bn']);
                //$pkgData['name'] = addslashes($pkgData['name']);
				//alone remove end
                $pkgData['product_id'] = $pkgData['goods_id'];
                $pkg[] = $pkgData['goods_id'];
                $pkgData['is_type'] = 'pkg';
                $pkgData['addon'] = addslashes(serialize($pkgData['addon']));
                $rs = $this->db->query('SELECT * FROM sdb_order_items WHERE order_id='.$pkgData['order_id'].' AND is_type = \'pkg\' AND product_id='.intval($pkgData['goods_id']));
                $sqlString = $this->db->GetUpdateSQL($rs, $pkgData,true);
//                $this->db->exec("UPDATE sdb_products SET freez = freez + ".intval($aData['nums'])." WHERE product_id = ".intval($aData['product_id']));
//                $this->db->exec("UPDATE sdb_products SET freez = ".intval($aData['nums'])." WHERE product_id = ".intval($aData['product_id'])." AND freez IS NULL");
                $this->db->exec($sqlString);
            }
            $this->db->exec('DELETE FROM sdb_order_items WHERE order_id='.$pkgData['order_id'].' AND is_type = \'pkg\' AND product_id NOT IN('.implode(',',$pkg).')');
        }

        //+促销信息------------------------------------------------------------
        if ($trading['pmt_o']['pmt_ids']) {//促销
            $sSql = 'INSERT INTO sdb_order_pmt (pmt_id,pmt_describe,order_id) select pmt_id,pmt_describe,\''.$data['order_id'].'\' FROM sdb_promotion WHERE pmt_id in('.implode(',',$trading['pmt_o']['pmt_ids']).')';
            $this->db->exec($sSql);
            foreach($trading['pmt_o']['pmt_ids'] as $k=>$pmtId) {
                $sSql = 'UPDATE sdb_order_pmt SET pmt_amount='.$trading['pmt_o']['pmt_money'][$k].' WHERE pmt_id='.intval($pmtId).' AND order_id='.$data['order_id'];
                $this->db->exec($sSql);
            }
        }
        if ($trading['products']) {
            $pre_pmtOrder = array();
            foreach ($trading['products'] as $v) {
                if ($v['pmt_id']){
                    $pre_pmtOrder[$v['pmt_id']] += $v['price'] - $v['_pmt']['price'];
                }
            }
            $aPmtIds = array_keys($pre_pmtOrder);
            if(!empty($aPmtIds)){
                $sSql = 'SELECT pmt_id,pmt_describe FROM sdb_promotion WHERE pmt_id IN('.implode(',', $aPmtIds).')';
                $aPmtOrder = $this->db->select($sSql);
                foreach($aPmtOrder as $k=>$v) {
                    $v['pmt_amount'] = $pre_pmtOrder[$v['pmt_id']];
                    $v['order_id'] = $data['order_id'];

                    $rs = $this->db->query('select * from sdb_order_pmt where 0=1');
                    $sqlString = $this->db->GetInsertSQL($rs, $v);
                    $this->db->exec($sqlString);
                }
            }
        }

        //+积分处理------------------------------------------------------------
        $oMemberPoint = $this->system->loadModel('trading/memberPoint');
        $oGift = $this->system->loadModel('trading/gift');
        $aGiftData = array();
        if ($data['score_u']>0) {
            if (!$oMemberPoint->payAllConsumePoint($data['member_id'],$data['order_id'])) {
                ;
            }else{
                //+赠品处理------------------------------------------------------------
                if (is_array($trading['gift_e']) && count($trading['gift_e'])) {
                    foreach($trading['gift_e'] as $giftId => $v) {
                        $giftId = $v['gift_id'];
                        $aGiftData[$giftId] = array(
                            'gift_id' => $giftId,
                            'name' => $v['name'],
                            'nums' => $v['nums'],
                            'point' => $v['point']);
                        if (!$oGift->freezStock($v['gift_id'], $v['nums'])) {//兑换赠品缺货
                            ;
                        }
                    }
                }
            }
        }
        if (is_array($trading['gift_p']) && count($trading['gift_p'])){
            foreach($trading['gift_p'] as $v) {
                $giftId = $v['gift_id'];
                if (isset($aGiftData[$giftId])) {
                    $aGiftData[$giftId]['nums'] += $v['nums'];
                }else {
                    $aGiftData[$giftId] = array(
                            'gift_id' => $giftId,
                            'name' => $v['name'],
                            'nums' => $v['nums'],
                            'point' => $v['point']);
                }
            }
        }
        if($aGiftData) {
            foreach($aGiftData as $item) {
                $oGift = $this->system->loadModel('trading/gift');
                $item['order_id'] = $data['order_id'];
                $rs = $this->db->query('select * from sdb_gift_items where 0=1');
                $sqlString = $this->db->GetInsertSQL($rs, $item);
                $this->db->exec($sqlString);
            }
        }

        //+优惠券------------------------------------------------------------
        if (is_array($trading['coupon_u']) && !empty($trading['coupon_u'])) {
            $oCoupon = $this->system->loadModel('trading/coupon');
            foreach ($trading['coupon_u'] as $code => $v) {
                $aTmp = $this->db->selectRow('select cpns_name from sdb_coupons where cpns_id='.intval($v['cpns_id']));
                $aData = array(
                    'order_id' => $data['order_id'],
                    'cpns_id' => $v['cpns_id'],
                    'memc_code' => $code,
                    'cpns_name' => $aTmp['cpns_name'],
                    'cpns_type' => $v['cpns_type']);
                $rs = $this->db->query('select * from sdb_coupons_u_items where 0=1');
                $sqlString = $this->db->GetInsertSQL($rs, $aData);
                $this->db->exec($sqlString);

//                echox($v['cpns_id'], $code, $data['order_id'], $data['member_id']);exit;

                $oCoupon->applyMemberCoupon($v['cpns_id'], $code, $data['order_id'], $data['member_id']);
            }
        }

        if (is_array($trading['coupon_p']) && !empty($trading['coupon_p'])) {
            foreach ($trading['coupon_p'] as $code => $v) {
                $aData = array(
                    'order_id' => $data['order_id'],
                    'cpns_id' => $v['cpns_id'],
                    'cpns_name' => $v['cpns_name'],
                    'nums' => $v['nums']);
                $rs = $this->db->query('select * from sdb_coupons_p_items where 0=1');
                $sqlString = $this->db->GetInsertSQL($rs, $aData);
                $this->db->exec($sqlString);
            }
        }
        $this->fireEvent('create',$data,$data['member_id']);        //订单生成成功事件
        return $data['order_id'];
    }

	function load($order_id){
        if($row = $this->db->selectrow('SELECT * from sdb_orders where order_id ='.$order_id)){
            $this->update_last_modify($order_id);
            $this->_info['order_id'] = $row['order_id'];        //会员id
            $this->_info['member_id'] = $row['member_id'];        //会员id
            $this->_info['confirm'] = $row['confirm']=='Y';
            $this->_info['status'] = $row['status'];        //状态：active:活动,  dead:死单, finish:完成
            $this->_info['pay_status'] = $row['pay_status'];        //是否支付(0 未支付 1 已支付 2 处理中 3 部分付款 4 部分退款 5 全额退款)
            $this->_info['ship_status'] = $row['ship_status'];        //发货状态：0未发货，1已发货，2部分发货，3部分退货，4已退货
            $this->_info['user_status'] = $row['user_status'];        //用户交互状态(null:无；payed:已支付；shipped:已收到货)
            $this->_info['is_delivery'] = $row['is_delivery'];        //是否实体配送Y;N
            $this->_info['weight'] = $row['weight'];        //重量
            $this->_info['tostr'] = $row['tostr'];        //文字描述
            $this->_info['acttime'] = $row['acttime'];        //活动时间
            $this->_info['createtime'] = $row['createtime'];        //创建时间
            $this->_info['itemnum'] = $row['itemnum'];        //货物总数量
            $this->_info['ip'] = $row['ip'];        //下单ip地址
            $this->_info['currency'] = $row['currency'];        //货币
            $this->_info['cur_rate'] = $row['cur_rate'];        //货币汇率
            $this->_info['payment'] = $row['payment'];        //支付方式
            $this->_info['memo'] = $row['memo'];        //订单备注
            $this->_info['receiver']['name'] = $row['ship_name'];        //收货人姓名
            $this->_info['receiver']['area'] = $row['ship_area'];        //收货人地qu
            $this->_info['receiver']['addr'] = $row['ship_addr'];        //收货人地址
            $this->_info['receiver']['zip'] = $row['ship_zip'];        //收货人邮编
            $this->_info['receiver']['tel'] = $row['ship_tel'];        //收货人固定电话
            $this->_info['receiver']['email'] = $row['ship_email'];        //收货人Email
            $this->_info['receiver']['mobile'] = $row['ship_mobile'];        //收货人移动电话
            $this->_info['shipping']['id'] = $row['shipping_id'];        //配送方式
            $this->_info['shipping']['time'] = $row['ship_time'];        //要求到货时间
            $this->_info['shipping']['method'] = $row['shipping'];        //配送方式
            $this->_info['shipping']['cost'] = $row['cost_freight'];        //配送价格
            $this->_info['shipping']['is_protect'] = $row['is_protect'];        //保价价格
            $this->_info['shipping']['protect'] = $row['cost_protect'];        //保价价格
            $this->_info['shipping']['area'] = $row['shipping_area'];        //配送地区
            $this->_info['basic']['totalPrice'] = $row['cost_item'];        //商品价格
            $this->_info['is_tax'] = $row['is_tax'];        //税 (仅商品)
            $this->_info['cost_tax'] = $row['cost_tax'];        //税 (仅商品)
            $this->_info['tax_company'] = $row['tax_company'];        //税 (仅商品)
            $this->_info['use_pmt'] = $row['use_pmt'];
            $this->_info['discount'] = $row['discount'];
            $this->_info['use_pmt'] = $row['use_pmt'];
            $this->_info['score_g'] = $row['score_g'];
            $this->_info['score_u'] = $row['score_u'];
            $this->_info['advance'] = $row['advance'];        //返点到预存款
            $this->_info['amount']['total'] = $row['total_amount'];
            $this->_info['amount']['final'] = $row['final_amount'];
            $this->_info['amount']['payed'] = $row['payed'];        //现已支付金额：应等于payments表本order所有money的和
            $this->_info['amount']['cost_payment'] = $row['cost_payment'];
            $this->_info['amount']['pmt_amount'] = $row['pmt_amount'];
            $this->_info['pay_extend'] = $row['extend'];
            $this->_info['last_change_time']=$row['last_change_time'];
			//alone add start
			$this->_info['bill_period'] = $row['bill_period'];
			//alone add end
            $this->_inDatabase = true;

            switch($row['payment']){
                case 0:
                $this->_info['paymethod'] = __('线下支付');
                $this->_info['paytype'] = 'OFFLINE';
                break;
                case -1:
                $this->_info['paymethod'] = __('货到付款');
                $this->_info['paytype'] = 'PAYAFT';
                break;
                default:
                $payment = $this->system->loadModel('trading/payment');
                $aPayment = $payment->getPaymentById($row['payment']);
                $this->_info['paymethod'] = $aPayment['custom_name'];
                $this->_info['paytype'] = $aPayment['pay_type'];
                break;
            }

            $oCur = $this->system->loadModel('system/cur');
            $aCur = $oCur->getSysCur();
            $this->_info['cur_name'] = $aCur[$row['currency']];

            return $this->_info;
        }return false;
    }

	//前台订单支付更换支付方式
    function chgPayment($orderid, $paymentid, $paymoney,$chgpayment=0){
		//error_log(print_r(func_get_args(),true),3,__FILE__.'.func.log');	//alone
		//error_log(print_r($_POST,true),3,__FILE__.'.POST.log');	//alone
        if($aOrder = $this->getFieldById($orderid, array('cost_protect','cost_freight','cost_tax','cost_payment','cost_item','pmt_amount','discount','payment','total_amount','payed','cost_payment','currency','cur_rate','bill_period'))){
            if($aOrder['payment'] != $paymentid){
                $payment = $this->system->loadModel('trading/payment');
                if($paymentid > 0){
                    $aPayment = $payment->getPaymentById($paymentid);
					//error_log(print_r($aPayment,true),3,__FILE__.'.aPayment.log');	//alone
                }else{
                    $aPayment['fee'] = 0;
                }
                if (!$chgpayment)
                    $aData['payment'] = $paymentid;

                $total_fee = 0;
                $total_fee = 0;
                $payedamount = $payment->getSuccOrderBillList($orderid);
                if ($payedamount){
                    foreach($payedamount as $pk => $pv){
                        $totalPayedMoney +=$pv['money'];//已支付总金额
                        $totalPayFee +=$pv['paycost'];//已支付费率
                    }
                }
                $chgMoney = $totalPayedMoney - $totalPayFee;
                $amountExceptPay = $aOrder['cost_protect']+$aOrder['cost_freight']+$aOrder['cost_tax']+$aOrder['cost_item']-$aOrder['discount'];
                $amountPayment = ($amountExceptPay - $chgMoney) * $aPayment['fee'];
                $total_amount = $amountExceptPay + $amountPayment + $totalPayFee;
				//alone add start
				$aData['bill_period'] = $_POST['icbc_period'];
				//alone add end
                $aData['cost_payment'] = $totalPayFee + $amountPayment;
                $aData['total_amount'] = $total_amount;
                $aData['final_amount'] = $total_amount * $aOrder['cur_rate'];
                $_POST['cur_money'] = ($aData['total_amount']-$chgMoney) * $aOrder['cur_rate'];
				//error_log(print_r($aData,true),3,__FILE__.'.aData.log');	//alone
                $rs = $this->db->exec('SELECT * FROM sdb_orders WHERE order_id =\''.$orderid.'\'');
                $sql = $this->db->getUpdateSQL($rs, $aData);
                $this->db->exec($sql);
                return $aData['total_amount']-$chgMoney;
            }else{
				//alone add start 当改变的支付方式都是icbc时,更新分期数
				$payment = $this->system->loadModel('trading/payment');
                if($paymentid > 0){
                    $aPayment = $payment->getPaymentById($paymentid);
					//error_log(print_r($aPayment,true),3,__FILE__.'.aPayment.log');	//alone
					if ($aPayment['pay_type'] == 'icbc')
					{
						$aData['bill_period'] = $_POST['icbc_period'];
						$rs = $this->db->exec('SELECT * FROM sdb_orders WHERE order_id =\''.$orderid.'\'');
						$sql = $this->db->getUpdateSQL($rs, $aData);
						$this->db->exec($sql);
					}
				}
				//alone add end
                return $paymoney;
            }
        }else{
            return false;
        }
    }
}
?>
